import React, { FC, useMemo } from 'react';
import { Chart, Geom, Axis, Tooltip, Coord, Legend, Guide } from 'bizcharts';
import { Empty } from 'antd';

import { defaultColors } from '@/constants/chartColors';

const { Html } = Guide;

const { Global } = G2; // 获取 Global 全局对象
Global.registerTheme('newTheme', {
  colors: defaultColors,
});

type LegendPosition =
  | 'left-top'
  | 'left-center'
  | 'left-bottom'
  | 'right-top'
  | 'right-bottom'
  | 'right-center'
  | 'top-left'
  | 'top-center'
  | 'top-right'
  | 'bottom-left'
  | 'bottom-center'
  | 'bottom-right';

export interface RingColumnProps {
  /** 图表数据 */
  data: Array<object>;
  /** X轴变量 */
  axisX: string;
  /** Y轴变量 */
  axisY: string;
  /** 图表高度 */
  height?: number;
  /** 图表内部padding */
  padding?: [number, number, number, number];
  /** 设置图例的显示位置 */
  position?: LegendPosition;
  /** 内部极坐标系的半径 */
  innerRadius?: number;
}

const RingDiagram: FC<RingColumnProps> = props => {
  const {
    data = [],
    height = 300,
    axisX,
    axisY,
    position = 'bottom-center',
    innerRadius = 0.55,
    padding,
  } = props;

  const totalData = useMemo(() => {
    let count = 0;
    data.map(item => {
      count += item.count;
    });

    return count;
  }, [data]);

  return (
    <div>
      {data.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <Chart theme="newTheme" height={height} data={data} padding={padding} forceFit>
          <Coord type={'theta'} radius={1} innerRadius={innerRadius} />
          <Axis name={axisX} />
          <Legend position={position} />

          <Geom
            type="intervalStack"
            position={axisY}
            color={axisX}
            tooltip={[
              `${axisX}*${axisY}`,
              (axisX, axisY) => {
                return {
                  name: axisX,
                  value: axisY,
                };
              },
            ]}
            style={{
              lineWidth: 1,
              stroke: '#fff',
            }}
          ></Geom>

          <Tooltip
            showTitle={false}
            itemTpl='<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
          />
          <Guide>
            <Html
              position={['50%', '50%']}
              html={`<div style="color:#8c8c8c;font-size:12px;text-align: center;width: 10em;"><span style="color:#44566C;font-size:21px">${totalData}</span>份</div>`}
              alignX="middle"
              alignY="middle"
            />
          </Guide>
        </Chart>
      )}
    </div>
  );
};

export default RingDiagram;
